<template>
  <div></div>
</template>

<script setup lang="ts">
  import { ref, watch } from 'vue'
  import { ElMessageBox } from 'element-plus'
  import { useUserStore } from '../../store/modules/user'
  import { useRouter, useRoute } from 'vue-router'

  const router = useRouter()
  const route = useRoute()
  const UserStore = useUserStore()

  const time = ref() // 时间差

  // 过期提醒
  const expireTip = () => {
    ElMessageBox.confirm('登录状态已过期，请重新登录!', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error',
    })
      .then(async () => {
        UserStore.logout()
        router.push({ path: '/login/index' })
      })
      .catch(() => {
        expireTip()
      })
  }

  // 获取时间
  const getTime = setInterval(() => {
    if (localStorage.getItem('token') && route.path != '/login/index') {
      const nowTime = new Date().getTime() // 当前时间
      const tokenStartTime = JSON.parse(localStorage.getItem('tokenStartTime')) // 开始时间
      time.value = nowTime - tokenStartTime
    }
  }, 1000)

  // 监听token
  watch(
    () => time.value,
    (newVal, oldVal) => {
      if (localStorage.getItem('token') && route.path != '/login/index') {
        const timeOver = JSON.parse(localStorage.getItem('timeOver')) * 60 * 60 // 过期时间
        if (newVal > timeOver) {
          clearInterval(getTime)
          expireTip()
        }
      }
    },
  )
</script>

<style scoped lang="scss"></style>
